因為前兩篇的 Notification,
在圖示上只能使用本地或 DataUrl,
因此打算從 DataUrl 下手的...沒想到..
以下是錯誤示範, 會導致上圖的錯誤
manifest.json
{
"manifest_version": 2,
"name": "ironman6",
"version": "1.0",
"browser_action": {
"default_popup": "index.html"
}
}
index.html
<title>ironman6</title>
<style>body {width: 500px;}</style>
<button id="showImage">Show Image</button>
<script src="app.js"></script>
app.js
window.addEventListener("load", function() {
document.querySelector("#showImage").addEventListener("click", showImage);
});
function showImage(){
var imgData = pngToBase64('http://ithelp.ithome.com.tw/ironman6/img/ironman6_logo.png');
chrome.notifications.create(
'Notifier' + Date.now(), {
type: 'image',
iconUrl: imgData,
title: 'Ironman6',
message: 'Day 15',
imageUrl: imgData
},
function(notificationId) {
console.log(notificationId);
}
);
}
function pngToBase64(imgSrc){
var img = new Image();
img.style.left = '-10000px';
img.style.width = '64px';
img.style.height = '64px';
img.style.position = 'absolute';
document.body.appendChild(img);
img.onload = function(){
var canvas = document.createElement('canvas'),
context = canvas.getContext("2d"),
iWidth = this.offsetWidth,
iHeight = this.offsetHeight,
output = [];
canvas.width = iWidth;
canvas.height = iHeight;
context.drawImage(this, 0, 0, iWidth, iHeight);
return canvas.toDataURL();
};
img.src = imgSrc;
return img.onload();
}
解法其實很簡單,
將 manifest.json 再加一條 permissions 變成下面那樣就行了
{
"manifest_version": 2,
"name": "ironman6",
"version": "1.0",
"browser_action": {
"default_popup": "index.html"
},
"permissions": [
"notifications",
"http://ithelp.ithome.com.tw/"
]
}
由此一來連用來轉換的 pngToBase64 函數也省了, 直接給網址就行.
function showImage(){
var imgData = 'http://ithelp.ithome.com.tw/ironman6/img/ironman6_logo.png';
chrome.notifications.create(
'Notifier' + Date.now(), {
type: 'image',
iconUrl: imgData,
title: 'Ironman6',
message: 'Day 15',
imageUrl: imgData
},
function(notificationId) {
console.log(notificationId);
}
);
}
雖然這次走斜門歪道繞了很大一圈,
不過最大的收穫反而是沒派上用場的 pngToBase64 ,
總覺得將來在哪可以用到XD